package cn.sxt.service.impl;

import cn.sxt.DataGridView;
import cn.sxt.domain.BillType;
import cn.sxt.domain.Bills;
import cn.sxt.mapper.BillTypeMapper;
import cn.sxt.mapper.BillsMapper;
import cn.sxt.service.BillsService;
import cn.sxt.vo.BillsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/5/8 9:12
 */
//暴露服务注解
@Service
public class BillsServiceImpl implements BillsService {
    @Autowired
    private BillTypeMapper billTypeMapper;

    @Autowired
    private BillsMapper billsMapper;

    @Override
    public DataGridView findAll(BillsVo billsVo) {
        // 使用mp自带的分页
        Page<Bills> page = new Page<>(billsVo.getPage(), billsVo.getLimit());
        // 按分类查询
        QueryWrapper<Bills> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(billsVo.getTypeId() != null, "type_id", billsVo.getTypeId());
        // 按时间查询
        queryWrapper.ge(billsVo.getStartTime() != null, "bill_time", billsVo.getStartTime());
        queryWrapper.le(billsVo.getEndTime() != null, "bill_time", billsVo.getEndTime());
        // 按时间排序
        queryWrapper.orderByDesc("bill_time");
        billsMapper.selectPage(page, queryWrapper);
        // 拿到所有的查询记录
        List<Bills> resords = page.getRecords();
        for (Bills bills : resords) {
            if(bills.getTypeId() == null){
                continue;
            }
            BillType billType = billTypeMapper.selectById(bills.getTypeId());

            bills.setTypeName(billType.getName());
        }
        //组装返回类
        return new DataGridView(page.getTotal(), resords);
    }

    @Override
    public void addBill(Bills bills) {
        bills.setBillTime(new Date());
        this.billsMapper.insert(bills);
    }
}
